<template>
	<view>
		<view style="width: 100vw;height: 735rpx; position:absolute;top: -200rpx;left: 0;">
			<image :src="require('../images/searchBg.jpg')" style="width: 100%;height: 100%"></image>
		</view>
		<view class="paddingL20" style="position:relative;z-index: 1;height: calc(100vh - 82rpx);">
			<view class="bg_white paddingL15 taxContent" style="">
				<view style="text-align: center;margin-bottom: 20rpx;font-size: 32rpx;font-weight: 600">税务授权登录</view>
				<view>
					<uv-steps :current="active">
						<uv-steps-item v-for="(item, index) in list1" :key="index">
							<template v-slot:title>
								<view :style="{ color: index == 1 ? '#333' : '#999' }">{{ item.title }}</view>
							</template>
						</uv-steps-item>
					</uv-steps>
				</view>
			</view>
			<view class="bg_white paddingL15 formStyle" style="">
				<uni-forms :modelValue="companyForm" ref="companyRef" :rules="companyRules">
					<view style="margin-bottom: 15rpx">纳税人识别号:</view>
					<uni-forms-item label="">
						<uni-easyinput v-model="companyForm.texNumber" disabled :inputBorder="false"></uni-easyinput>
					</uni-forms-item>
					<view style="margin-bottom: 15rpx">企业名称:</view>
					<uni-forms-item label="">
						<uni-easyinput v-model="companyForm.companyName" disabled :inputBorder="false"></uni-easyinput>
					</uni-forms-item>
					<view v-if="!provinceName" style="margin-bottom: 15rpx">所属省份:</view>
					<uni-forms-item v-if="!provinceName" label="" ref="province" required name="province">
						<picker @change="provinceChange" :value="provinceIndex" :range="provinceList">
							<text class="textStyle"
								:style="{ color: companyForm.province ? '#000' : '#999', 'font-size': companyForm.province ? '26rpx' : '24rpx' }"
								style="padding-right: 10px;margin-top: 20rpx;">{{ companyForm.province ?
									companyForm.province :
									'请选择企业所在省份' }}</text>
						</picker>
					</uni-forms-item>
					<view style="margin-bottom: 15rpx">电子税务局账号:</view>
					<uni-forms-item label="" ref="taxAccount" name="taxAccount">
						<uni-easyinput :trim="true" v-model="companyForm.taxAccount" placeholder="请输入手机号" maxlength="11"
							@input="changeValidate($event, 'taxAccount')" :clearable="false"></uni-easyinput>
					</uni-forms-item>
					<view style="margin-bottom: 15rpx">登录密码:</view>
					<uni-forms-item label="" ref="taxPassword" name="taxPassword">
						<uni-easyinput :trim="true" type="password" v-model="companyForm.taxPassword"
							placeholder="请输入税务密码" @input="changeValidate($event, 'taxPassword')"
							:clearable="false"></uni-easyinput>
					</uni-forms-item>

				</uni-forms>

				<button @click="loginBtnFun" :disabled="btnLoading" class="loginStyle" type="primary"
					:loading="btnLoading">授权登录</button>

				<view class="row" style="justify-content: center;margin-top: 20rpx">
					<checkbox-group @change="isChecked = !isChecked" style="width: auto">
						<checkbox color="#f2891c" style="transform:scale(0.7);" :checked="isChecked" shape="circle">
						</checkbox>
					</checkbox-group>
					<view>阅读并同意 <text style="color: #0A98D5;" @click="toAgreement">《授权协议》</text></view>
				</view>
			</view>
		</view>
		<view>
			<uni-popup ref="popup" :maskClick="false" background-color="#fff">
				<view class="popup-content">
					<view style="margin-bottom: 20rpx">温馨提示</view>
					<!-- 需要爬取数据 -->
					<view v-if="isloading">
						<view style="margin: 60rpx 0">
							<uni-load-more status="loading" :iconSize="70" :showText="false" />
						</view>
						<view style="color: #488AFD;margin-top: 90rpx">授权中，请耐心等待...</view>
					</view>
					<!-- 不需要爬取数据 -->
					<view v-else>
						<view style="width: 125rpx;height: 110rpx;margin: 0 auto">
							<image :src="require('../images/successIcon.png')" style="width: 100%;height: 100%"></image>
						</view>
						<view style="font-size: 32rpx;color: #222222;margin-top: 20rpx">授权成功</view>
						<view style="color: #999999;font-size: 26rpx;margin-top: 20rpx">请勿在5分钟内登录税局系统！</view>
						<view class="dialogBtn" @click="givePowerFun" style="">点击完成授权（{{ time }}）</view>
					</view>
				</view>
			</uni-popup>
		</view>
		<taxLoginPopup @searchSuccess="searchSuccess" ref="taxLoginPopupRef"></taxLoginPopup>
	</view>
</template>

<script>
import {
	onlyAccountApi,
	taxAppLogin
} from "@/api/water";
import { getProvince } from "@/api/public";
import Routine from '@/libs/routine'
import cache from "@/utils/cache";
import { deleteSpuid } from '@/utils/auth'
import taxLoginPopup from './components/taxLoginPopup'
export default {
	components: {
		taxLoginPopup
	},
	data() {
		return {
			time: 3,
			timer: null,
			disabled: false,
			isloading: true,
			btnLoading: false,
			notNeedCode: ["zhejiang", "hubei", "guangdong"],
			provinceIndex: 0,
			provinceList: [],
			provinceListObj: [],
			active: 1,
			list1: [{
				title: '公司信息'
			}, {
				title: '税务信息'
			}, {
				title: '获取数据'
			}],
			texNumber: '',
			isChecked: false,
			companyRules: { // 表单验证规则
				taxAccount: {
					rules: [{
						required: true,
						errorMessage: '请输入手机号'
					},
					{
						validateFunction: (rule, value, data, callback) => {
							return new Promise((resolve, reject) => {
								if (!value) {
									reject(new Error("手机号不能为空"))
									// return callback(new Error("手机号不能为空"));
								} else {
									const reg = /^1[3-9][0-9]\d{8}$/;
									if (reg.test(value)) {
										resolve();
									} else {
										reject(new Error("请输入正确的手机号"))
									}
								}
							}).then(result => {
							}).catch(error => {
							});
						},
						errorMessage: '手机号码不正确',
					}
					]
				},
				taxPassword: {
					rules: [{
						required: true,
						errorMessage: '请输入税务密码'
					}]
				},
			},
			countDown: 60,
			provinceName: '',
			provinceId: '',
			enterpriseId: '',
			companyForm: {
				texNumber: '',
				companyName: '',
				taxAccount: '',
				taxPassword: '',
				phoneCode: '',
			},
		}
	},
	onLoad(options) {
		this.companyForm.texNumber = options?.tax
		this.companyForm.companyName = options?.companyName
		this.provinceName = options?.provinceName
		this.provinceId = options?.provinceId
		this.getProvinceList()
	},
	onReady() {
		this.$nextTick(() => {
			this.$refs.companyRef.setRules(this.companyRules)
		})
	},
	methods: {
		searchSuccess(val) {
			this.isloading = val
			this.$refs.popup.open('center')
			if (!val) {
				this.TimeLink()
			}
		},
		loginBtnFun() {
			if (!this.isChecked) {
				return this.$util.Tips('请先同意授权协议')
			}
			this.$refs.companyRef.validate().then(async (validate) => {
				if (validate) {

					if (this.notNeedCode.includes(this.provinceName)) {
						await this.noteNeedCodeLogin()  // 根据省份有不需要验证码登录
					} else {
						await this.firstLogin() //需要验证码
					}

				}
			})
			let params = {
				Um_Key_ButtonName: `授权登录-${this.companyForm.companyName}`,
				Um_Key_SourcePage: '税务授权登录',
			}
			this.$umaTrack.pageClickTrack(params)
		},
		givePowerFun() {
			clearInterval(this.timer);
			this.$refs.popup.close()
			this.time = 3;
			uni.switchTab({
				url: '/pages/reportList/index'
			})
		},
		//不需要验证码
		noteNeedCodeLogin() {
			this.btnLoading = true
			let par = cache.get('params') ? JSON.parse(cache.get('params')) : {}
			let obj = {
				provinceName: this.provinceName,
				creditCode: this.companyForm.texNumber.trim(),
				phone: this.companyForm.taxAccount.trim(),
				password: this.companyForm.taxPassword.trim(),
				provinceId: this.provinceId,
				taxpayerName: this.companyForm.companyName,
				shareUid: par.spreadUid || 0,
				source: par.spreadUid ? 'share' : 'query',
				// #ifdef MP
				channelType: 'routine',
				// #endif
				// #ifdef H5
				channelType: Routine.isWeixin() ? 'wechat' : 'h5',
				// #endif

				// #ifdef MP-TOUTIAO
				channelType: 'tiktok'
				// #endif
			}
			onlyAccountApi(obj).then((notNeed) => {
				if (notNeed.code === 200) {
					deleteSpuid()
					this.enterpriseId = notNeed.data.enterpriseId
					this.$refs.popup.open('center')
					this.isloading = true
					this.TimeLink()

				}
			}).finally(() => {
				this.btnLoading = false
			})
		},


		//倒计时3秒后跳转
		TimeLink() {
			this.timer = setInterval(() => {
				this.time--;
				if (this.time < 0) {
					clearInterval(this.timer);
					this.time = 3;
					uni.switchTab({
						url: '/pages/reportList/index'
					})
				}
			}, 1000);
		},

		async firstLogin() {
			this.btnLoading = true
			let par = cache.get('params') ? JSON.parse(cache.get('params')) : {}
			let params = {
				creditCodeOrTaxPayerId: this.companyForm.texNumber,
				phoneNumber: this.companyForm.taxAccount.trim(),
				provinceName: this.provinceName,
				provinceId: this.provinceId,
				taxpayerName: this.companyForm.companyName.trim(),
				password: this.companyForm.taxPassword.trim(),
				shareUid: par.spreadUid || 0,
				source: par.spreadUid ? 'share' : 'query',
				// #ifdef MP
				channelType: 'routine',
				// #endif
				// #ifdef H5
				channelType: Routine.isWeixin() ? 'wechat' : 'h5',
				// #endif

				// #ifdef MP-TOUTIAO
				channelType: 'tiktok'
				// #endif
			}
			taxAppLogin(params).then(res => {
				if (res.code == 200) {
					deleteSpuid()
					if (res.data.code !== 0) {
						return this.$util.Tips(res.data.message)
					}
					if (res.data.needVerifyCode) {
						const sendCodeForm = {
							account: res.data.account
						}
						let infoOBj = {
							taskId: res.data.queryTaskId,
							creditCode: this.companyForm.texNumber,
						}
						const codeForm = {
							province: this.provinceName,
							creditCode: this.companyForm.texNumber,
							uuid: res.data.uuid,
							webUuid: res.data.webUuid,
							account: res.data.account,
							password: this.companyForm.taxPassword,
							enterpriseId: res.data.enterpriseId
						}
						//需要验证码
						this.$refs.taxLoginPopupRef.open(sendCodeForm, codeForm, infoOBj)
					} else {
						//不需要验证码 弹框倒计时
						this.isloading = true
						this.$refs.popup.open('center')
						this.TimeLink()
					}
				}
			}).finally(() => {
				this.btnLoading = false
			})
		},
		async getProvinceList() {
			let res = await getProvince()
			if (res.code === 200) {
				this.provinceListObj = res.data
				this.provinceList = this.provinceListObj.map(v => v.name)
			}
		},
		provinceChange(val) {
			this.provinceIndex = val.detail.value
			this.$set(this.companyForm, 'province', this.provinceList[val.detail.value])
			this.provinceListObj.forEach(item => {
				if (this.companyForm.province == item.name) {
					this.provinceId = item.id
					this.provinceName = item.pinyin
				}
			})
		},
		changeValidate(e, ref) {
			this.$refs[ref].onFieldChange(e)
		},
		toAgreement() {
			uni.navigateTo({
				url: '/pages/privacy/authorizationAgreement'
			})
		}
	}
}
</script>

<style lang="scss" scoped>
/* #ifdef MP-TOUTIAO */
/deep/ .uv-steps-item__line--row {
	left: 120rpx !important;
}

/deep/ .uv-steps {
	justify-content: space-between;
}

/* #endif */
.taxContent {
	margin-top: 30rpx;
	padding-top: 30rpx;
	border-radius: 20rpx;
	padding-bottom: 20rpx;
	height: 244rpx;
}

/deep/.uni-forms-item__label {
	display: none !important;
}

.loginStyle {
	width: 100%;
	background: linear-gradient(90deg, #488AFD 0%, #3F9BF9 100%);
	text-align: center;
	color: white;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	margin-top: 25rpx;
	overflow: hidden;
}

/deep/ uni-checkbox .uni-checkbox-input {
	border-radius: 50%;
}

.formStyle {
	margin-top: 30rpx;
	border-radius: 20rpx;
	padding-top: 30rpx;
	padding-bottom: 50rpx;
}

.codeStyle {
	background: #488AFD;
	color: white;
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx;
	border-radius: 0 40rpx 40rpx 0;
}

.codeDisabledStyle {
	background: #CCCCCC;
	color: white;
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx 0 30rpx;
	border-radius: 0 40rpx 40rpx 0;
}

.popup-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	//justify-content: center;
	padding: 25px 15px 15px;
	height: 540rpx;
	background-color: #fff;
	text-align: center;
	width: 520rpx;
	margin: 0 auto;
	position: relative;
	border-radius: 20rpx;
	z-index: 999;
}

/deep/ .uni-popup .uni-popup__wrapper {
	border-radius: 25rpx;
}

.dialogBtn {
	width: 408rpx;
	height: 72rpx;
	line-height: 72rpx;
	background: #488AFD;
	border-radius: 30rpx;
	color: white;
	margin-top: 40rpx;
}

/deep/ .uni-easyinput__content-input {
	height: 80rpx;
}

/deep/ .uni-easyinput__content {}

.textStyle {
	height: 88rpx;
	width: 100%;
	display: block;
	border: 1px solid rgb(229, 229, 229);
	line-height: 88rpx;
	padding-left: 20rpx;
}
</style>